<script setup lang="ts">
import { ref, computed, onMounted, markRaw } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ElMenu, ElMenuItem, ElSubMenu, ElIcon, ElInput, ElTooltip, ElBadge
} from 'element-plus'
import {
  Odometer, Monitor, Avatar, List, Files, DataAnalysis,
  Search, Star, Clock
} from '@element-plus/icons-vue'

interface MenuItemType {
  id: string
  title: string
  icon?: unknown
  route?: string
  badge?: number
  starred?: boolean
  children?: MenuItemType[]
}

// Props
interface Props {
  collapsed?: boolean
}

withDefaults(defineProps<Props>(), {
  collapsed: false
})

// 路由相关
const route = useRoute()
const router = useRouter()
const currentRoute = computed(() => route.path)

// 搜索功能
const searchKeyword = ref('')
const showSearch = ref(false)

// 菜单数据
const menuItems = ref<MenuItemType[]>([
  {
    id: 'dashboard',
    title: '仪表板',
    icon: markRaw(Odometer),
    route: '/dashboard',
    starred: true
  },
  {
    id: 'devices',
    title: '设备管理',
    icon: markRaw(Monitor),
    badge: 2,
    children: [
      { id: 'device-list', title: '设备列表', route: '/devices' },
      { id: 'device-groups', title: '设备分组', route: '/devices/groups' },
      { id: 'device-monitor', title: '设备监控', route: '/devices/monitor' }
    ]
  },
  {
    id: 'accounts',
    title: '账号管理',
    icon: markRaw(Avatar),
    badge: 5,
    children: [
      { id: 'account-list', title: '账号列表', route: '/accounts' },
      { id: 'account-import', title: '批量导入', route: '/accounts/import' },
      { id: 'account-groups', title: '账号分组', route: '/accounts/groups' }
    ]
  },
  {
    id: 'tasks',
    title: '任务中心',
    icon: markRaw(List),
    badge: 3,
    children: [
      { id: 'task-list', title: '任务列表', route: '/tasks' },
      { id: 'task-templates', title: '任务模板', route: '/tasks/templates' },
      { id: 'task-schedule', title: '定时调度', route: '/tasks/schedule' },
      { id: 'task-history', title: '执行历史', route: '/tasks/history' }
    ]
  },
  {
    id: 'content',
    title: '内容库',
    icon: markRaw(Files),
    route: '/content'
  },
  {
    id: 'analytics',
    title: '数据分析',
    icon: markRaw(DataAnalysis),
    route: '/analytics',
    starred: true
  }
])

// 收藏菜单
const starredItems = computed(() => 
  menuItems.value.filter(item => item.starred)
)

// 搜索过滤
const filteredMenuItems = computed(() => {
  if (!searchKeyword.value.trim()) {
    return menuItems.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return menuItems.value.filter(item => {
    const matchTitle = item.title.toLowerCase().includes(keyword)
    const matchChildren = item.children?.some(child => 
      child.title.toLowerCase().includes(keyword)
    )
    return matchTitle || matchChildren
  })
})

// 方法
const toggleSearch = () => {
  showSearch.value = !showSearch.value
  if (showSearch.value) {
    // 下一帧聚焦搜索框
    setTimeout(() => {
      const input = document.querySelector('.menu-search input') as HTMLInputElement
      input?.focus()
    }, 100)
  } else {
    searchKeyword.value = ''
  }
}

const toggleStar = (item: MenuItemType) => {
  item.starred = !item.starred
}

const goToRoute = (route: string) => {
  router.push(route)
}

// 快捷键支持
onMounted(() => {
  const handleKeydown = (e: KeyboardEvent) => {
    // Ctrl/Cmd + K 打开搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
      e.preventDefault()
      toggleSearch()
    }
    // Escape 关闭搜索
    if (e.key === 'Escape' && showSearch.value) {
      toggleSearch()
    }
  }
  
  document.addEventListener('keydown', handleKeydown)
  
  // 清理事件监听器
  return () => {
    document.removeEventListener('keydown', handleKeydown)
  }
})
</script>

<template>
  <div class="custom-menu" :class="{ collapsed }">
    <!-- 搜索区域 -->
    <div class="menu-header">
      <div v-if="showSearch || !collapsed" class="search-container">
        <el-input
          v-if="showSearch"
          v-model="searchKeyword"
          class="menu-search"
          placeholder="搜索菜单... (Ctrl+K)"
          :prefix-icon="Search"
          size="small"
          clearable
        />
        <el-tooltip 
          v-else
          content="搜索菜单 (Ctrl+K)"
          placement="right"
          :disabled="!collapsed"
        >
          <el-icon 
            class="search-trigger"
            :class="{ active: showSearch }"
            @click="toggleSearch"
          >
            <Search />
          </el-icon>
        </el-tooltip>
      </div>
    </div>

    <!-- 收藏菜单 -->
    <div v-if="starredItems.length > 0 && !collapsed" class="starred-section">
      <div class="section-title">
        <el-icon><Star /></el-icon>
        <span>收藏</span>
      </div>
      <div class="starred-items">
        <div
          v-for="item in starredItems"
          :key="item.id"
          class="starred-item"
          :class="{ active: currentRoute === item.route }"
          @click="item.route && goToRoute(item.route)"
        >
          <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
          <span class="item-title">{{ item.title }}</span>
        </div>
      </div>
    </div>

    <!-- 主菜单 -->
    <el-menu
      :default-active="currentRoute"
      :collapse="collapsed"
      :unique-opened="true"
      router
      class="main-menu"
    >
      <template v-for="item in filteredMenuItems" :key="item.id">
        <!-- 有子菜单的项目 -->
        <el-sub-menu v-if="item.children" :index="item.id">
          <template #title>
            <div class="menu-item-content">
              <el-icon v-if="item.icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-title">{{ item.title }}</span>
              <el-badge
                v-if="item.badge && item.badge > 0"
                :value="item.badge"
                :max="99"
                class="menu-badge"
              />
            </div>
            <el-icon
              v-if="!collapsed"
              class="star-icon"
              :class="{ starred: item.starred }"
              @click.stop="toggleStar(item)"
            >
              <Star />
            </el-icon>
          </template>
          
          <el-menu-item
            v-for="child in item.children"
            :key="child.id"
            :index="child.route"
          >
            <span>{{ child.title }}</span>
            <el-badge
              v-if="child.badge && child.badge > 0"
              :value="child.badge"
              :max="99"
              class="child-badge"
            />
          </el-menu-item>
        </el-sub-menu>

        <!-- 无子菜单的项目 -->
        <el-menu-item v-else :index="item.route">
          <el-icon v-if="item.icon">
            <component :is="item.icon" />
          </el-icon>
          <template #title>
            <div class="menu-item-content">
              <span class="menu-title">{{ item.title }}</span>
              <el-badge
                v-if="item.badge && item.badge > 0"
                :value="item.badge"
                :max="99"
                class="menu-badge"
              />
              <el-icon
                v-if="!collapsed"
                class="star-icon"
                :class="{ starred: item.starred }"
                @click.stop="toggleStar(item)"
              >
                <Star />
              </el-icon>
            </div>
          </template>
        </el-menu-item>
      </template>
    </el-menu>

    <!-- 最近访问 -->
    <div v-if="!collapsed" class="recent-section">
      <div class="section-title">
        <el-icon><Clock /></el-icon>
        <span>最近访问</span>
      </div>
      <div class="recent-items">
        <div class="recent-item">
          <span class="recent-title">设备列表</span>
          <span class="recent-time">2分钟前</span>
        </div>
        <div class="recent-item">
          <span class="recent-title">任务模板</span>
          <span class="recent-time">5分钟前</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.custom-menu {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  
  &.collapsed {
    .menu-header {
      padding: 8px 0;
    }
  }
}

.menu-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .search-container {
    position: relative;
    
    .search-trigger {
      font-size: 18px;
      color: var(--el-text-color-regular);
      cursor: pointer;
      padding: 8px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover, &.active {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
    }
  }
}

.starred-section, .recent-section {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-bottom: 12px;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }
}

.starred-items {
  display: flex;
  flex-direction: column;
  gap: 4px;
  
  .starred-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: var(--el-color-primary-light-9);
    }
    
    &.active {
      background: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
    }
    
    .item-title {
      font-size: 14px;
    }
  }
}

.main-menu {
  flex: 1;
  border: none;
  overflow-y: auto;
  
  .menu-item-content {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
    
    .menu-title {
      flex: 1;
    }
    
    .menu-badge {
      :deep(.el-badge__content) {
        font-size: 10px;
        padding: 0 4px;
        height: 16px;
        line-height: 16px;
        min-width: 16px;
      }
    }
  }
  
  .star-icon {
    opacity: 0;
    transition: all 0.2s;
    cursor: pointer;
    
    &:hover, &.starred {
      opacity: 1;
      color: var(--el-color-warning);
    }
  }
  
  :deep(.el-menu-item):hover .star-icon,
  :deep(.el-sub-menu__title):hover .star-icon {
    opacity: 1;
  }
  
  .child-badge {
    :deep(.el-badge__content) {
      font-size: 10px;
      padding: 0 4px;
      height: 14px;
      line-height: 14px;
      min-width: 14px;
    }
  }
}

.recent-items {
  .recent-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: var(--el-fill-color-lighter);
    }
    
    .recent-title {
      font-size: 13px;
      color: var(--el-text-color-primary);
    }
    
    .recent-time {
      font-size: 11px;
      color: var(--el-text-color-placeholder);
    }
  }
}

// 滚动条样式
:deep(*) {
  &::-webkit-scrollbar {
    width: 4px;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background: var(--el-border-color);
    border-radius: 2px;
    
    &:hover {
      background: var(--el-border-color-darker);
    }
  }
}
</style>